<template>
  <section class="d-flex f-align">
    <el-avatar :src="'/'+imageUrl+'?imageView2/1/w/80/h/80'" v-if="!progressFlag"></el-avatar>
    <el-progress
      type="circle"
      :percentage="progressPercent"
      :stroke-width="4"
      :width="42"
      v-show="progressFlag"
    ></el-progress>
    <el-upload
      class="img-btn"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadImg"
    >
      <el-button type="primary" plain round size="mini" class="ml-20">更改头像</el-button>
    </el-upload>
  </section>
</template>

<script>
import { fileUpload } from "api/file/index";
import { uploadAvatar } from "api/user";
export default {
  props: ["avatar"],
  data() {
    return {
      imageUrl: "",
      progressFlag: false,
      progressPercent: 0,
      fileType: ["image/gif", "image/png", "image/jpeg"]
    };
  },
  watch: {
    avatar(val) {
      if (val) {
        this.imageUrl = val;
      }
    }
  },
  methods: {
    uploadImg(f) {
      this.progressFlag = true;
      let formdata = new FormData();
      formdata.append("image", f.file);
      fileUpload(formdata, {
        onUploadProgress: progressEvent => {
          this.progressPercent =
            (progressEvent.loaded / progressEvent.total) * 100;
        }
      }).then(res => {
        this.imageUrl = f.file;
        this.$emit("getAvaTar", res.data[0].fileUrl);
        if (this.progressPercent === 100) {
          this.progressFlag = false;
          this.progressPercent = 0;
        }
      });
    },
    // 上传图片前的过滤
    beforeAvatarUpload(file) {
      const isImg = this.fileType.some(o => o === file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImg) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isImg && isLt2M;
    }
  }
};
</script>

<style lang='scss' scoped>
</style>
